#include "sr.h"

static int state;

#define READY 1
#define RUNNING 2

void
initCheckPosDesired(void) {
    state = READY;
}

void
checkPosDesiredFire(double posdesired, int hasEventFlags, int *craneKnownFlags, 
        int *cranePresentFlags) {

    if(state == RUNNING) {
        if(GET_BIT(hasEventFlags, POSDESIREDBIT)) {
            if(posdesired < -4.0 || posdesired > 4.0) {
                SET_BIT_TRUE(*craneKnownFlags, EMSTOPCHECKPOSDESIREDBIT);
                SET_BIT_TRUE(*cranePresentFlags, EMSTOPCHECKPOSDESIREDBIT);

                initCheckPosDesired();
            }
        }
    }

    if(!GET_BIT(*craneKnownFlags, EMSTOPCHECKPOSDESIREDBIT)) {
        SET_BIT_TRUE(*craneKnownFlags, EMSTOPCHECKPOSDESIREDBIT);
    }
}

void
checkPosDesiredPostfire(int hasEventFlags, int craneKnownFlags, int cranePresentFlags) {

    switch(state) {
        case READY : {
            if(GET_BIT(craneKnownFlags, TRIGGERBIT)) {
                if(GET_BIT(cranePresentFlags, TRIGGERBIT) && 
                        GET_BIT(hasEventFlags, SHUTDOWNBIT)) {
                    state = RUNNING;
                }
            }
        } break;
        
        case RUNNING: {
            if(GET_BIT(hasEventFlags, SHUTDOWNBIT)) {
                initCheckPosDesired();
                break;
            }
            
            if(GET_BIT(craneKnownFlags, EMSTOPMERGERBIT)) {
                if(GET_BIT(cranePresentFlags, EMSTOPMERGERBIT)) {
                    initCheckPosDesired();
                }
            }
        } break;
    }
}
